/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/6/12
 */
import { computed, reactive, toRaw } from 'vue'
import { byId, check, RootNode, getFormData, delAll, installResults } from '../lib/form'
import { error } from './util'
import { getFormComponentRules } from './library'
import type { IChannelModelField } from '@/model'

// 模型主表数据
export const mainFormData = reactive<{ [keys: string]: any }>({})

// 更新模型主表数据
export const updateMainFormData = (field: string, val: any) => {
    mainFormData[field] = val
}

// 获取模型字段数据
export const getFormFieldData = () => {
    if (RootNode.length === 0) {
        error('请设置模型字段信息')
        return
    }
    const formData = []
    let isValid = true
    // TODO 这里需要考虑嵌套的情况，但是因为表单构建的时候嵌套组件有BUG未解决，放在后面在处理
    for (const item of RootNode) {
        const ctx = byId(item)
        if (ctx === undefined) continue
        // 获取表单数据
        const data = toRaw(ctx.formData)
        if (!checkField(ctx, data)) {
            isValid = false
            break
        }
        formData.push(data)
    }
    if (!isValid) return

    return formData
}

/**
 * 验证字段信息
 * @param ctx
 * @param data
 */
const checkField = (ctx: any, data: { [keys: string]: any }) => {
    const rules = getFormComponentRules(ctx.type)
    let valid = true
    console.log(data)
    rules.forEach((item) => {
        if (item.required && !data[item.field!]) {
            valid = false
            error(`请完善字段【${item.label}】`)
        }
    })
    return valid
}

/**
 * 获取提交后端的结果数据结果数据
 */
export const getResults = () => {
    if (!check()) {
        return
    }
    const fieldData = getFormFieldData()
    if (!fieldData) {
        return
    }

    return {
        main: getFormData(),
        results: fieldData,
    }
}

/**
 * 将获取的后端数据解析为表单数据
 */
export const parserResults = (results: IChannelModelField[]) => {
    // 清理原数据
    delAll()
    results.forEach((item) => {
        installResults(item)
    })
}
